package com.chookss.home.interview;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.base.Token;
import com.chookss.home.entity.ContactEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.ScreenshotUtil;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.SelectDialogListener;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

//一键面试
public class InterviewDetailActivity extends BaseAct {


    @BindView(R.id.rlTitle)
    RelativeLayout rlTitle;
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.tvCompany2)
    TextView tvCompany2;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvRefresh)
    TextView tvRefresh;
    @BindView(R.id.tvTime)
    TextView tvTime;
    @BindView(R.id.tvTime2)
    TextView tvTime2;
    @BindView(R.id.llData)
    LinearLayout llData;
    @BindView(R.id.ivQrcode)
    ImageView ivQrcode;
    @BindView(R.id.iv_download)
    ImageView ivDownload;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.llArrow)
    LinearLayout llArrow;
    @BindView(R.id.ivUser1)
    ImageView ivUser1;
    @BindView(R.id.tvUser1)
    TextView tvUser1;
    @BindView(R.id.ivUser2)
    ImageView ivUser2;
    @BindView(R.id.tvUser2)
    TextView tvUser2;
    @BindView(R.id.tvArrow)
    TextView tvArrow;
    @BindView(R.id.lluser2)
    LinearLayout lluser2;
    @BindView(R.id.ivUser3)
    ImageView ivUser3;
    @BindView(R.id.tvUser3)
    TextView tvUser3;
    @BindView(R.id.lluser3)
    LinearLayout lluser3;
    @BindView(R.id.ivUser4)
    ImageView ivUser4;
    @BindView(R.id.tvUser4)
    TextView tvUser4;
    @BindView(R.id.lluser4)
    LinearLayout lluser4;
    @BindView(R.id.llUser)
    LinearLayout llUser;
    private String key, examName, examCode, qrCodeValid, period;
    private String companyName, companyCode, addressType;
    private List<ContactEntity> selectList=new ArrayList<>();
    private boolean isShowBottomView=false;
    private String employeeCodes="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_interview_detail);
        ButterKnife.bind(this);
        tvRefresh.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); //下划线
        tvRefresh.getPaint().setAntiAlias(true);//抗锯齿
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this,"1","06");
        dialogList.add("保存图片");
        dialogList.add("取消");
        examCode = getIntent().getStringExtra("examCode");
        examName = getIntent().getStringExtra("examName");
        qrCodeValid = getIntent().getStringExtra("qrCodeValid");
        if(Utils.isNull(qrCodeValid)){
            qrCodeValid="180";
        }
        tvName.setText(examName);
        tvTime.setText("二维码有效期" + Utils.secondChangeMinute(qrCodeValid));
        tvCompany.setText(new ShareUtils().getString(this, StaticClass.COMPANYNAME, ""));
        companyName = new ShareUtils().getString(InterviewDetailActivity.this, StaticClass.COMPANYNAME, "");
        companyCode = new ShareUtils().getString(InterviewDetailActivity.this, StaticClass.COMPANYCODE, "");
        employeeCodes = new ShareUtils().getString(InterviewDetailActivity.this, StaticClass.EMPLOYEECODE, "");
        if (Utils.isNull(companyName)) {
            companyName = getResources().getString(R.string.app_name);
        }
        if (Utils.isNull(companyCode)) {
            companyCode = "COM202107290001";
        }
        if (Urls.baseUrl.contains("dev_kmer")) {
            addressType = "1";
        } else {
            addressType = "0";
        }
        selectList.addAll(MyApp.contactEntityLogList);
        MyApp.contactEntityLogList.clear();
        GlideUtils.loadCustomRound(this,new ShareUtils().getString(this, StaticClass.USER_AVATAR_URL, ""),ivUser1,R.drawable.default_user_head,8);
        tvUser1.setText(new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        employeeCodes=new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
        if(selectList!=null){
            if(selectList.size()>0){
                lluser2.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(this,selectList.get(0).getHeadPhotoThumbUrl(),ivUser2,R.drawable.default_user_head,8);
                tvUser2.setText(selectList.get(0).getEmployeeName());
                employeeCodes=employeeCodes+","+selectList.get(0).getEmployeeCode();
            }
            if(selectList.size()>1){
                lluser3.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(this,selectList.get(1).getHeadPhotoThumbUrl(),ivUser3,R.drawable.default_user_head,8);
                tvUser3.setText(selectList.get(1).getEmployeeName());
                employeeCodes=employeeCodes+","+selectList.get(1).getEmployeeCode();
            }
            if(selectList.size()>2){
                lluser4.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(this,selectList.get(2).getHeadPhotoThumbUrl(),ivUser4,R.drawable.default_user_head,8);
                tvUser4.setText(selectList.get(2).getEmployeeName());
                employeeCodes=employeeCodes+","+selectList.get(2).getEmployeeCode();
            }
        }
        ivArrow.setBackgroundResource(R.drawable.icon_zhankai2_up);
        getData();
    }

    private void getData() {
        showLoading();
        Map<String, String> map = new HashMap<>();
        map.put("examCode", examCode);
        map.put("qrCodeValid", qrCodeValid);
        MyHttpRequest.postRequest(Urls.getInterViewCountDown, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if(tvTime2==null){
                            return;
                        }
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        key = jsonObject1.getString("key");
                        period = jsonObject1.getString("period");
                        tvTime2.setText(period);
                        String name = companyName;
                        try {
                            name = URLEncoder.encode(companyName, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                       String url = Urls.webBaseUrl + "interview.html#/login?examCode=" + examCode + "&companyCode=" + companyCode + "&companyName=" + name + "&key=" + key + "&validDate=" + qrCodeValid + "&addressType=" + addressType+"&employeeCodes="+employeeCodes+"&generateCode="+new ShareUtils().getString(InterviewDetailActivity.this, StaticClass.EMPLOYEECODE, "")+"&token=" + Token.INSTANCE.getToken();
                        KLog.i(url);
                        initView(url);
                    }else{
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initView(String url) {
        Observable.just(url).map(new Function<String, Bitmap>() {
            @Override
            public Bitmap apply(String s) throws Exception {
                return setQrImage(url, Utils.dip2px(InterviewDetailActivity.this, 192));
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        try {
                            Glide.with(InterviewDetailActivity.this).load(bitmap).into(ivQrcode);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private Bitmap setQrImage(String text, int size) {

        try {
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.MARGIN, 0); // 设置白边
            /*
             * 设置容错级别，默认为ErrorCorrectionLevel.L
             * 因为中间加入logo所以建议你把容错级别调至H,否则可能会出现识别不了
             */
//            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            BitMatrix bitMatrix = new QRCodeWriter().encode(text,
                    BarcodeFormat.QR_CODE, size, size, hints);
            int[] pixels = new int[size * size];
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < size; y++) {
                for (int x = 0; x < size; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * size + x] = 0xff000000;
                    } else {
                        pixels[y * size + x] = 0xffffffff;
                    }
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(size, size,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, size, 0, 0, size, size);
            return bitmap;
        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void requestSTORAGE() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            showDialog();
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(InterviewDetailActivity.this, denied, quick);
                    }
                });
    }

    private BottomListsDialog bottomListsDialog;
    private List<String> dialogList = new ArrayList<>();

    private void showDialog() {
        bottomListsDialog = new BottomListsDialog(this, dialogList, new SelectDialogListener() {
            @Override
            public void onCancel() {
            }

            @Override
            public void onListItemClick(int position, List<String> list) {
                if (position == 0) {
                    tvCompany2.setVisibility(View.VISIBLE);
                    tvRefresh.setVisibility(View.GONE);
                    tvCompany.setText("欢迎您进入面试");
                    tvCompany2.setText(companyName);
                    Observable.timer(300, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Long>() {
                                @Override
                                public void accept(Long aLong) {
                                    ScreenshotUtil.saveScreenshotFromActivity(InterviewDetailActivity.this);
                                }
                            });

                }
                bottomListsDialog.dismiss();
            }
        });
        bottomListsDialog.setSelect(0);
        bottomListsDialog.show();
    }

    @OnClick({R.id.ivBack, R.id.iv_download, R.id.tvRefresh,R.id.llArrow, R.id.lluser1, R.id.lluser2, R.id.lluser3, R.id.lluser4})
    public void onClick(View view) {
        Intent intent=null;
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.iv_download:
                requestSTORAGE();
                break;
            case R.id.tvRefresh:
                getData();
                break;
            case R.id.llArrow:
                if(isShowBottomView){
                    isShowBottomView=false;
                    tvArrow.setText("查看本次面试的面试官");
                    ivArrow.setBackgroundResource(R.drawable.icon_zhankai2_up);
                    llUser.setVisibility(View.GONE);
                }else{
                    isShowBottomView=true;
                    tvArrow.setText("本次面试的面试官");
                    ivArrow.setBackgroundResource(R.drawable.icon_zhankai2_down);
                    llUser.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.lluser1:
                intent=new Intent(this, PersonalHomeActivity.class);
                intent.putExtra("employeeCode", new ShareUtils().getString(InterviewDetailActivity.this, StaticClass.EMPLOYEECODE, ""));
                startActivity(intent);
                break;
            case R.id.lluser2:
                intent=new Intent(this, PersonalHomeActivity.class);
                intent.putExtra("employeeCode", selectList.get(0).getEmployeeCode());
                startActivity(intent);
                break;
            case R.id.lluser3:
                intent=new Intent(this, PersonalHomeActivity.class);
                intent.putExtra("employeeCode", selectList.get(1).getEmployeeCode());
                startActivity(intent);
                break;
            case R.id.lluser4:
                intent=new Intent(this, PersonalHomeActivity.class);
                intent.putExtra("employeeCode", selectList.get(2).getEmployeeCode());
                startActivity(intent);
                break;
        }
    }
}
